﻿
layui.use(['form','table','upload','laytpl','layedit'], function(){
  var $ = layui.$
      ,form = layui.form
      ,layer = layui.layer
      ,table = layui.table
      ,upload = layui.upload
      ,layedit = layui.layedit
      ,laytpl = layui.laytpl;

  var checkbox_union_list = [];

  form.on('radio(type)', function(data){
    if(data.value == 2){
      $(".type1").hide();
      $(".type2").show();
    } else {
      $(".type1").show();
      $(".type2").hide();
    }
  });

  var uploadInst = upload.render({
    elem: '#uploadImg'
    ,url: "/upload-img"
    ,before: function(obj){
      obj.preview(function(index, file, result){
        $('#previewImg').attr('src', result); //图片链接（base64）
      });
    }
    ,done: function(res){
      //上传成功
      if (res.code == 0) {
        console.log(res.data.imageUrl);
        $('#market_image').val(res.data.imageUrl);
        $('#previewImg').attr('src', res.data.imageUrl);
      }else{//上传失败
        return layer.msg('上传失败');
      }
    }
    ,error: function(){
      //演示失败状态，并实现重传
      var demoText = $('#demoText');
      demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
      demoText.find('.demo-reload').on('click', function(){
        uploadInst.upload();
      });
    }
  });

  $(document).on('click','.open-union',function(){
    layer.open({
      type: 1,
      shadeClose: true,
      content: $('#union-list-div'),
      title : '选择联盟',
      area: ['600px', '580px'],
      success: function(layero, index){
        table.render({
          elem: '#unionList'
          ,url: "/union-list"
          ,cols: [[
            {field:'id',type:'checkbox',width:60,}
            ,{field:'union_name', title: '联盟名称'}
            ,{field:'receive_order_price', width:120, title: '接受价格'}
            ,{field:'offer_price', width:100, title: '出价', edit: 'text'}
          ]]
          ,page: {
            layout: ['prev', 'page', 'next']
          }
          ,id: 'idUnion'
          ,done: function(res, curr, count){

            var checkboxUnionIds = getCheckboxUnionIds();
            for (var i = 0; i < res.data.length; i++) {
              if($.inArray(res.data[i]['id'],checkboxUnionIds) > -1){
                res.data[i]["LAY_CHECKED"]='true';
                var index= res.data[i]['LAY_TABLE_INDEX'];
                $('tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true);
                $('tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked');
              }
            }
          }
        });
      }
    });
  });


  table.on('checkbox(unionList)', function(obj){
    if(obj.checked === false){
      delCheckboxUnionIds(obj.data.id);
    }

    var checkStatus = table.checkStatus('idUnion')
        ,data = checkStatus.data;

    var union_select_html = '';
    $.each(data,function(k,v){
      var union_id = v.id;
      var union_name = v.union_name;
      union_select_html += '<span class="layui-badge layui-bg-gray union-select-each union-select-'+union_id+'">'+union_name+'<i class="layui-icon union-del" data-union_id="'+union_id+'"></i></span>';

      var checkboxUnionIds = getCheckboxUnionIds();
      if($.inArray(union_id,checkboxUnionIds) == -1){
        checkbox_union_list.push(v);
      }

    });
    union_select_html += '<button type="button" class="layui-btn layui-btn-primary layui-btn-sm open-union union-select-each"><i class="layui-icon"></i></button>';
    $('.union-select').html(union_select_html);

    $("#checkbox-union-list").val(JSON.stringify(checkbox_union_list));
  });

  $('#content').on('blur',function(){
    var that = $(this);
    var content = $.trim(that.val());
    if(!content){
      layer.msg('文案内容不能为空');
      return false;
    }
    $.getJSON("/task-parsing",{content:content},function(obj){
      if(obj.code === 0){
        $('#title').val(obj.data.good_short_title);
        $('#image').val(obj.data.good_main_image);
        $('#activity_id').val(obj.data.coupon_activity_id);
        $('#goods_id').val(obj.data.good_item_id);
        $('#commission_rate').val(obj.data.good_ratio);
        $('#price_last_coupon').val(obj.data.price_last_coupon);
        var platform = obj.data.good_istmall == 1 ? 2 : 1;
        $(":radio[name='platform'][value='" + platform + "']").prop("checked", "checked");
        form.render();
      }else{
        layer.msg('请根据模板完善文案信息');
      }
    });
  });

  $(document).on('click','.union-del',function(){
    var union_id = $(this).data('union_id');
    $('.union-select .union-select-'+union_id).remove();

    delCheckboxUnionIds(union_id);

    $("#checkbox-union-list").val(JSON.stringify(checkbox_union_list));
  });

  function getCheckboxUnionIds(){
    var unionIds = [];
    for (var i = 0; i < checkbox_union_list.length; i++){
      unionIds.push(checkbox_union_list[i]['id']);
    }
    return unionIds;
  }

  function delCheckboxUnionIds(union_id){
    for (var i = 0; i < checkbox_union_list.length; i++){
      if(union_id == checkbox_union_list[i].id){
        checkbox_union_list.splice(i, 1);
      }
    }
  }







  var sucai_box_index = 0;
  var layedit_index = [];
  $('.sucai-tupian-btn').on('click',function(){
    if(!checkSucaiIsEmpty()){
      layer.msg('有空白素材块，请上传、填写或移除');
      return false;
    }

    var getTpl = $('#sucai-tupian').html();
    var data = {
      index: sucai_box_index
    };
    laytpl(getTpl).render(data, function(html){
      $('.sucai-info').append(html);
    });

    upload_sucai_image(sucai_box_index);

    sucai_box_index++;
  });
  $('.sucai-wenzi-btn').on('click',function(){
    if(!checkSucaiIsEmpty()){
      layer.msg('有空白素材块，请上传、填写或移除');
      return false;
    }

    var getTpl = $('#sucai-wenzi').html();
    var data = {
      index: sucai_box_index
    };
    laytpl(getTpl).render(data, function(html){
      $('.sucai-info').append(html);
    });
    layedit_index[sucai_box_index] = layedit.build('sucai-input-'+sucai_box_index,{
      tool: ['face']
    }); //建立编辑器
    console.log(layedit_index);
    sucai_box_index++;
  });


  $('.sucai-shipin-btn').on('click',function(){
    if(!checkSucaiIsEmpty()){
      layer.msg('有空白素材块，请上传、填写或移除');
      return false;
    }

    var getTpl = $('#sucai-shipin').html();
    var data = {
      index: sucai_box_index
    };
    laytpl(getTpl).render(data, function(html){
      $('.sucai-info').append(html);
    });

    upload_sucai_video(sucai_box_index);

    sucai_box_index++;
  });

  $(document).on('click','.sucai-close-btn',function(){
    var index = $(this).attr('data-index');
    $(this).closest('.sucai-box').remove();
  });

  form.verify({
    sucai: function(value,item) {
      console.log(value);
      console.log(item);
      if(!value){
        return '有空白素材块，请上传、填写或移除';
      }

      $.each(layedit_index,function(key,val){
        layedit.sync(layedit_index[key]);
      });
      // return layedit.sync(layedit_index);
    }
  });

  function upload_sucai_image(index) {
    upload.render({
      elem: '#upload-'+index
      ,url: '/upload-img' //改成您自己的上传接口
      ,done: function(res){
        layer.msg('上传成功');
        var file = res.data.imageUrl;
        layui.$('#uploadView-'+index).removeClass('layui-hide').find('img').attr('src', file);
        layui.$('#sucai-input-'+index).val(file);
        console.log(res)
      }
    });
  }

  function upload_sucai_video(index) {
    upload.render({
      elem: '#upload-'+index
      ,url: '/upload-img' //改成您自己的上传接口
      ,accept: 'video'
      ,done: function(res){
        layer.msg('上传成功');
        var file = res.data.imageUrl;
        layui.$('#uploadView-'+index).removeClass('layui-hide').find('video').attr('src', file);
        layui.$('#sucai-input-'+index).val(file);
        console.log(res)
      }
    });
  }

  function checkSucaiIsEmpty() {
    $.each(layedit_index,function(key,val){
      layedit.sync(layedit_index[key]);
    });

    var flag = true;
    $('.sucai-input-textarea').each(function (index,element) {
      var value = $(element).val();
      if(!value){
        flag = false;
        return false;
      }
    });

    return flag;
  }


  /******朋友圈********/
  var layedit_friend = layedit.build('friend-copy',{
    tool: ['face']
  }); //建立编辑器



});